#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangAltdqPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_altdq_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "阿勒泰地区"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
    }

    def start_requests(self):
        for source, county, url, path in [
            ['阿勒泰地区人民政府', "", "https://www.xjalt.gov.cn/govxxgk/gov-listTwoPage.html", "首页>政府信息公开>法定主动公开内容>政府文件>部门文件"],
            ['阿勒泰地区人民政府', "", "https://www.xjalt.gov.cn/govxxgk/gov-listTwoPage.html", "首页>政府信息公开>法定主动公开内容>政府文件>行政规范性文件"],
            ['阿勒泰市人民政府', "阿勒泰市", "https://alt.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>政策法规>文件公开"],
            ['布尔津县人民政府', "布尔津县", "https://www.brj.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>政策法规>文件"],
            ['哈巴河县人民政府', "哈巴河县", "https://www.hbh.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>政策法规>政府法规>政府文件>部门文件"],
            ['吉木乃县人民政府', "吉木乃县", "https://www.jmn.gov.cn/govxxgk/gov-listTwoPage.html", "网站首页>政府信息公开>法定主动公开内容>政策法规>政府文件"],
            ['吉木乃县人民政府', "吉木乃县", "https://www.jmn.gov.cn/govxxgk/gov-listTwoPage.html", "网站首页>政府信息公开>法定主动公开内容>政策法规>规范性文件"],
            ['福海县人民政府', "福海县", "https://www.xjfhx.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>政策法规>规范性文件"],
            ['富蕴县人民政府', "富蕴县", "http://www.xjfy.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>文件政策>其他文件"],
            ['富蕴县人民政府', "富蕴县", "http://www.xjfy.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>文件政策>规范性文件"],
            ['青河县人民政府', "清河县", "http://www.xjqh.gov.cn/govxxgk/xxgk.html", "首页>政府信息公开>法定主动公开内容>政策法规>政府文件"],
        ]:

            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item, 'path': path}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        gov_listTwoPage = response.xpath("//script").re_first(r'="(.*gov-listTwoPage\.js)"')
        yield response.follow(gov_listTwoPage, callback=self.parse_js1, meta=meta, dont_filter=True)

    def parse_js1(self, response, **kwargs):
        meta = response.meta
        deptnum = response.xpath(""".""").re_first(r'deptnum\s*=\s*"(.*?)"')
        meta['deptcode'] = deptnum
        yield response.follow('/js/weblightfront.js', callback=self.parse_js2, meta=meta, dont_filter=True)

    def parse_js2(self, response, **kwargs):
        meta = response.meta
        siteGuid = response.xpath(""".""").re_first(r'siteGuid"\s*:\s*"(.*?)"')
        projectName = response.xpath(""".""").re_first(r'projectName"\s*:\s*"(.*?)"')
        category_api = response.xpath(""".""").re_first(r'projectName\s*\+\s*"(.*?getleftmenubydeptcode.*?)"')
        api = response.xpath(""".""").re_first(r'projectName\s*\+\s*"(.*?getgovinfolistalo.*?)"')
        data = {
            "token": "",
            "params": {
                "deptcode": meta['deptcode'],
                "siteGuid": siteGuid
            }
        }
        meta['data'] = data
        meta['projectName'] = projectName
        meta['api'] = api
        data = json.dumps(data, separators=(',', ':'))
        url = response.urljoin(projectName + category_api)
        yield scrapy.FormRequest(url, body=data, callback=self.parse_category, meta=meta, headers=self.headers,
                                 method="POST", dont_filter=True)

    def parse_category(self, response, **kwargs):
        meta = response.meta
        data = meta['data']
        for datas in response.json()['list']:
            for sub in datas.get('sublist', []):
                if sub['categoryname'] in meta['path'].split('>')[-1]:
                    data['params']['categorynum'] = sub['categorynum']
                for sub_sub in sub.get('sublist2', []):
                    if sub_sub['categoryname'] in meta['path'].split('>')[-1]:
                        data['params']['categorynum'] = sub_sub['categorynum']
                        break
                if data['params'].get('categorynum'):
                    break
            if data['params'].get('categorynum'):
                break
        data['params']['pageSize'] = '15'
        data['params']['pageIndex'] = '0'
        meta['data'] = data
        data = json.dumps(data, separators=(',', ':'))
        url = response.urljoin(meta['projectName'] + meta['api'])
        yield scrapy.FormRequest(url, body=data, callback=self.parse_list, meta=meta, headers=self.headers,
                                 method="POST", dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        datas = response.json()['custom']
        elem_list = datas['data']
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['infourl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['infodate']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'xlsx' in item['source_url'] or 'doc' in item['source_url'] or 'pdf' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta['data']
            pages = math.ceil(datas['total'] / 100)
            print(response.url, f"page: {pages}")
            for page_num in range(1, int(pages) + 1):
                data['params']['pageIndex'] = str(page_num)
                temp_data = json.dumps(data, separators=(',', ':'))
                yield scrapy.FormRequest(response.url, body=temp_data, callback=self.parse_list, headers=self.headers,
                                         meta={'item': prev_item, 'is_next': False},  method="POST", dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_altdq_policy".split())
